/**
 * 前端用户操作
 */

/**
 * 用户登录
 */
function doLogin(event) {
	var $loginBox = $('#loginBox');
	var data = {
		userNum : $loginBox.find('input[name=userNum]').val(),
		userPassword : $loginBox.find('input[name=password]').val()
	};
	$.ajax({
		url : 'login',
		data : {
			data : JSON.stringify(data)
		},
		type : 'post',
		dataType : 'json',
		success : function(data) {
			if (data.message == 'success') {
				location.href = data.page;
			} else {
				alert("登陆失败，账号不存在或密码错误");
			}
		}
	});
	event.stopPropagation();
}

// 注册数据验证
function dataVerify(event) {
	var $input = $(this);
	var type = $input.attr('name');
	var $span = $input.parent().next('span');
	if (type == 'petName') {
		var petName = $input.val();
		if(petName.length <2) {
			$span.attr('class', 'text-danger').html(
			'<i class="glyphicon glyphicon-remove"></i> 昵称长度不少于2个字符');
			return;
		}
		var data = {
			petName : petName
		};
		$
				.ajax({
					url : 'regist/petName',
					data : {
						data : JSON.stringify(data)
					},
					type : 'post',
					dataType : 'json',
					success : function(data) {
						if (data.repeat == 'yes') {
							$span
									.attr('class', 'text-danger')
									.html(
											'<i class="glyphicon glyphicon-remove"></i> 昵称已被使用');
						} else {
							$span.attr('class', 'text-success').html(
									'<i class="glyphicon glyphicon-ok"></i>');
						}
					}
				});
	} else if (type == 'userPassword') {
		var pwd = $input.val();
		if (pwd.length == 0) {
			$span.attr('class', 'text-danger').html(
					'<i class="glyphicon glyphicon-remove"></i> 密码不能为空');
		} else if (pwd.length < 6 || pwd.lenth > 16) {
			$span.attr('class', 'text-danger').html(
					'<i class="glyphicon glyphicon-remove"></i> 密码为6~16位');
		} else {
			$span.attr('class', 'text-success').html(
					'<i class="glyphicon glyphicon-ok"></i>');
		}
	} else if (type == 'surePassword') {
		var sure = $input.val();
		if (sure.length == 0) {
			$span.attr('class', 'text-danger').html(
					'<i class="glyphicon glyphicon-remove"></i> 密码不能为空');
		} else if (sure == $('#registBox input[name=userPassword]').val()) {
			$span.attr('class', 'text-success').html(
					'<i class="glyphicon glyphicon-ok"></i>');
		} else {
			$span.attr('class', 'text-danger').html(
					'<i class="glyphicon glyphicon-remove"></i> 密码不一致');
		}
	}
}

/**
 * 用户注册
 * 
 * @param event
 */
function doRegist(event) {
	var $user = $('#registBox input');
	var petName = $user.filter('[name = petName]').val();
	var pwd = $user.filter('[name = userPassword]').val();
	var surePwd = $user.filter('[name = surePassword]').val();
	if (pwd.length < 6 || pwd.lenth > 16 || pwd != surePwd
			|| $user.filter('[name = petName]').parent().next('span.text-success').length == 0) {
		return;
	}
	var data = {
		'petName' : petName,
		'userPassword' : pwd
	};
	$.ajax({
		url : 'regist',
		data : {
			data : JSON.stringify(data)
		},
		type : 'post',
		dataType : 'json',
		success : function(data) {
			if (data.regist == 'success') {
				alert('注册成功，您的账号为' + data.userNum);
			} else {
				alert('注册失败');
			}
		}
	});
	event.stopPropagation();
}

/**
 * 注销账户
 * 
 * @param event
 */
function logout(event) {
	event.preventDefault();
	$.ajax({
		url : '/SchoolEducationSystem/login/logout',
		data : {
			type : $(this).attr('data-roles')
		},
		type : 'post',
		success : function() {
			location.reload();
		}
	});
	event.stopPropagation();
}

/**
 * 更改密码(管理员)
 * @param event
 */
function changePasswordByAdmin(event) {
	var $user = $('#myModal');
	var oldPassword = $user.find('input[name=oldpassword]').val();
	var password = $user.find('input[name=password]').val();
	var surePassword = $user.find('input[name=surepassword]').val();
	if(password.length >= 6) {
		if(password == surePassword) {
			$.ajax({
				url : 'admin/changePassword',
				data : {
					oldPassword : oldPassword,
					newPassword : surePassword
				},
				type : 'post',
				dataType : 'json',
				success : function(data){
					if(data.update == 'success') {
						alert('修改成功');
						$('#myModal').modal('hide')
					} else {
						alert('修改失败');
					}
				}
			});
		} else {
			alert('密码输入不一致');
		}
	} else {
		alert('密码长度不够');
	}
}

function getSubscribeUserList(event) {
	$('body').animate({
		scrollTop : '0px'
	}, 800);
	var $user = $(this);
	var dataLocal = $user.data('user');
	var lessonId = $user.attr('data-id');
	if (dataLocal == null) {
		$
				.ajax({
					url : 'studentInfo',
					data : {
						lessonId : lessonId
					},
					type : 'post',
					dataType : 'json',
					success : function(data) {
						$user.data('user', 'data');
						var $stu = $('#studentList');
						var $panel = $('<div id="lesson' + lessonId
								+ '" class="tab-pane fade"></div>');
						var $table = $('<table class="table table-striped table-bordered table-hover"></table');
						$table
								.append('<tr><th>ID</th><th>账户</th><th>学生</th><th>订阅时间</th><th>状态</th><th>操作</th></tr>');
						for (var i = 0; i < data.length; i++) {
							var $tr = $('<tr data-id="' + data[i].id
									+ '"></tr>');
							$tr.append('<td>' + data[i].user.id + '</td>');
							$tr.append('<td>' + data[i].user.userNum + '</td>');
							$tr.append('<td>' + data[i].user.petName + '</td>');
							$tr.append('<td>' + data[i].user.createDate
									+ '</td>');
							if (data[i].state == 0) {
								$tr.append('<td class="text-danger">未通过</td>');
							} else if (data[i].state == 1) {
								$tr.append('<td class="text-warning">待审核</td>');
							} else {
								$tr
										.append('<td class="text-success">审核通过</td>');
							}
							$tr
									.append('<td><a class="btn btn-danger btn-xs" href="#" data-type="show"><i class="glyphicon glyphicon-info-sign"></i></a> '
											+ '<button class="btn btn-success btn-xs" type="button" data-type="2"><i class="glyphicon glyphicon-ok"></i></button> '
											+ '<button class="btn btn-danger btn-xs" type="button" data-type="0"><i class="glyphicon glyphicon-remove"></i></button></td>');
							$table.append($tr);
						}
						$table.find('td>a[data-type=show]').click(
								getStudentInfoByTeacher);
						$table.find('td>button[data-type]').click(
								auditByTeacher);
						$panel.append($table);
						$stu.append($panel);
						$user.trigger('click');
					}
				});
	}
}

/**
 * 审核学生
 * 
 * @param event
 */
function auditByTeacher(event) {
	var $btn = $(this);
	var state = $btn.attr('data-type');
	if ($btn.parent().prev().text() == '待审核') {
		$.ajax({
			url : 'studentInfo/audit',
			data : {
				subscribeId : $btn.parents('tr').attr('data-id'),
				state : state
			},
			type : 'post',
			dataType : 'json',
			success : function(data) {
				if (data.isLogin == 'no') {
					alert('用户尚未登陆，没有权限');
				} else {
					if (data.update == 'success') {
						if (state == 0) {
							$btn.parent().prev().attr('class', 'text-danger')
									.text('未通过');
						} else if (state == 2) {
							$btn.parent().prev().attr('class', 'text-success')
									.text('审核通过');
						}
						alert('提交成功');
					} else {
						alert('提交失败');
					}
				}
			}
		});
	} else {
		alert('已经审核，无法修改');
	}
}

function getStudentInfoByTeacher(event) {
	alert('student');
}

/**
 * 获取学生系别的相应专业（管理员）
 * 
 * @param event
 */
function getMajorList(event) {
	var $btnDeal = $(this);
	$('body').animate({
		scrollTop : '0px'
	}, 800);
	if ($btnDeal.data('typeData') != null) {
		return;
	}
	var typeId = $btnDeal.attr('data-id');

	$.ajax({
		url : 'studentMajor',
		data : {
			departmentId : typeId
		},
		type : 'post',
		dataType : 'json',
		success : function(data) {
			$btnDeal.data('typeData', 1);
			dealHtml(data);
		}
	});
	function dealHtml(data) {
		var $twoType = $('#twoType');
		var $div = $('<div id="type' + typeId + '" class="tab-pane fade">');
		var $table = $('<table class="table table-striped table-bordered table-hover"></table>');
		$table.append('<tr><th>ID</th><th>类别</th><th>操作</th></tr>');
		for (var i = 0; i < data.length; i++) {
			var $tr = $('<tr></tr>');
			$tr.append('<td>' + data[i].id + '</td>');
			$tr.append('<td id="twoTypeName' + data[i].id + '">'
					+ data[i].majorName + '</td>');
			$tr
					.append('<td><a href="#" class="btn btn-success btn-xs" data-id="'
							+ data[i].id
							+ '" data-toggle="modal" data-target="#myModal">修改</a> '
							+ '<a href="#" class="btn btn-danger btn-xs" data-type="delete" data-parent="twoType" data-id="'
							+ data[i].id + '">删除</a></td>');
			$tr.find('a[data-type=delete]').click(deleteDepartmentAndMajor);
			$tr.find('a[data-toggle=modal]').click(
					function(event) {
						var $btnCommit = $(this);
						var $typeName = $btnCommit.parent().prev()
						$('#typeUpdate').attr('data-id',
								$btnCommit.attr('data-id')).attr('data-type',
								'twoType');
						$('#myModal input[name=type]').val($typeName.text());
					});
			$table.append($tr);
		}
		$div.append($table);
		$twoType.append($div);
		$btnDeal.trigger('click');
	}
}

/**
 * 修改课程类型数据
 * 
 * @param event
 */
function updateDepartmentAndMajor(event) {
	var $btnCommit = $(this);
	var typeId = $btnCommit.attr('data-id');
	var $typeName = $('#myModal input[name=type]');
	var url = 'studentMajor/updateMajor';
	var data;
	var type;
	if ($btnCommit.attr('data-type') == 'oneType') {
		type = 'oneType';
		data = {
			id : typeId,
			name : $typeName.val()
		};
	} else if ($btnCommit.attr('data-type') == 'twoType') {
		type = 'twoType';
		data = {
			id : typeId,
			majorName : $typeName.val()
		};
	}
	$.ajax({
		url : url,
		data : {
			data : JSON.stringify(data),
			type : type
		},
		type : 'post',
		dataType : 'json',
		success : function(data) {
			if (data.isLogin == 'no') {
				alert('尚未登陆，没有权限')
			} else {
				if (data.update == 'success') {
					if (type == 'oneType') {
						$('#oneTypeName' + typeId).text($typeName.val());
					} else {
						$('#twoTypeName' + typeId).text($typeName.val());
					}
					alert('修改成功');
					$('#myModal').modal('hide')
				} else {
					alert('修改失败');
				}
			}
		}
	});
}

/**
 * 添加课程类型数据
 * 
 * @param event
 */
function addDepartmentAndMajor(event) {
	var typeName = $('#typeName').val();
	var $oneType = $('#oneType');
	var data;
	var url;
	if ($oneType.length == 0) {
		url = 'publishDepartment';
		data = {
			name : typeName
		};
	} else {
		url = 'publishMajor';
		data = {
			majorName : typeName,
			stuDepartment : {
				id : $oneType.val()
			}
		};
	}
	$.ajax({
		url : url,
		data : {
			data : JSON.stringify(data)
		},
		type : 'post',
		dataType : 'json',
		success : function(data) {
			if (data.isLogin == 'no') {
				alert('尚未登陆，没有权限');
			} else {
				if (data.save == 'success') {
					alert('添加成功');
					location.href = data.page;
				} else {
					alert('添加失败');
				}
			}
		}
	});
}

/**
 * 删除相应课程类型
 * 
 * @param event
 */
function deleteDepartmentAndMajor(event) {
	event.preventDefault();
	var $btnDelete = $(this);
	var type = $btnDelete.attr('data-parent');
	var typeId = $btnDelete.attr('data-id');
	$.ajax({
		url : 'studentMajor/deleteMajor',
		data : {
			typeId : typeId,
			type : type
		},
		type : 'post',
		dataType : 'json',
		success : function(data) {
			if (data.isLogin == 'no') {
				alert('尚未登陆，没有权限');
			} else {
				if (data.del == 'success') {
					alert('删除成功');
					$btnDelete.parent().parent().remove();
					if (type == 'oneType') {
						$('#type' + typeId).remove();
					}
				} else {
					alert('删除失败');
				}
			}
		}
	});
	event.stopPropagation();
}

/**
 * 根据系别获取专业（学生详细信息）
 * 
 * @param event
 */
function getMajorListByDepartment(event) {
	var $department = $(this);
	var departmentId = $department.val();
	var dataLocal = $department.data('majorList');
	if (dataLocal == null) {
		$.ajax({
			url : 'userInfo/major',
			data : {
				departmentId : departmentId
			},
			type : 'post',
			dataType : 'json',
			success : function(data) {
				$department.data('majorList', data);
				dealHtml(data);
			}

		});
	} else {
		dealHtml(dataLocal);
	}

	function dealHtml(data) {
		var $major = $('#major');
		$major.empty();
		for (var i = 0; i < data.length; i++) {
			$major.append('<option value="' + data[i].id + '">'
					+ data[i].majorName + '</option>');
		}
	}
}

/**
 * 更新用户详细信息
 * 
 * @param event
 */
function updateUserInfo(event) {
	var $userInfo = $('#updateUserInfo');
	var data = {
		petName : $userInfo.find('[name=petName]').val(),
		userInfo : {
			sex : $userInfo.find('[name=sex]:checked').val(),
			name : $userInfo.find('[name=name]').val(),
			birthday : $userInfo.find('[name=birthday]').val(),
			major : {
				id : $userInfo.find('[name=major]').val()
			},
			email : $userInfo.find('[name=email]').val(),
			phoneNum : $userInfo.find('[name=phoneNum]').val()
		}
	};
	$.ajax({
		url : 'userInfo',
		data : {
			data : JSON.stringify(data)
		},
		type : 'post',
		dataType : 'json',
		success : function(data) {
			if (data.isLogin == 'no') {
				alert('尚未登陆，没有权限');
			} else {
				if (data.update == 'success') {
					alert('提交成功');
					location.reload();
				} else {
					alert('提交失败');
				}
			}
		}
	});
}

function updateLogo(event) {
	$.ajax({
		url : 'userInfo/logo',
		data : {
			logo : $('#userLogo>img').attr('src')
		},
		type : 'post',
		dataType : 'json',
		success : function(data) {
			if (data.isLogin == 'no') {
				alert('尚未登陆，没有权限');
			} else {
				if (data.update == 'success') {
					alert('提交成功');
					location.reload();
				} else {
					alert('提交失败');
				}
			}
		}
	});
}

/**
 * 更改用户角色
 * @param event
 */
function updateUserRoles(event) {
	var $btnCommit = $(this);
	var rolesId = $btnCommit.parent().prev().children().val();
	var userId = $btnCommit.attr('data-id');
	var data = {
		id : userId,
		userRoles : {
			id : rolesId
		}
	};
	$.ajax({
		url : 'userRoles',
		data : {
			data : JSON.stringify(data)
		},
		type : 'post',
		dataType : 'json',
		success : function(data) {
			if (data.isLogin == 'no') {
				alert('尚未登陆，没有权限');
			} else {
				if (data.update == 'success') {
					alert('提交成功');
				} else {
					alert('提交失败');
				}
			}
		}
	});
}
